#-*-coding:utf-8-*-
from django import forms
from django.db.models import Q
from django.contrib.auth import authenticate


from DjangoCaptcha import Captcha


from .models import UserProfile


class LoginForm(forms.Form):
    username = forms.CharField(required=True, error_messages={'required':u'用户名不可为空'})
    password = forms.CharField(required=True, error_messages={'required':u'密码不可为空'})

    def clean_username(self):
        username = self.cleaned_data.get('username')
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
        except Exception as e:
            raise forms.ValidationError((u'用户名不存在'))
        return username

    def clean_password(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return password
            else:
                raise forms.ValidationError((u'密码错误'))
        except Exception as e:
            raise forms.ValidationError((u'密码错误'))